package com.rfs.thread;

import javax.sound.midi.Soundbank;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author renfushuai
 * @date 2022/6/6
 * 使用wait()、notify()和notifyAll()时需要先对调用对象加锁。
 */
public class WaitNotify {
    static boolean flag=true;
    static Object lock=new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread waitThread = new Thread(() -> {
            synchronized (lock) {
                while (flag) {
                    try {
                        System.out.println(Thread.currentThread() + " flag is true .wait @" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                        lock.wait();
                        System.out.println("wait .... ");
                    } catch (InterruptedException e) {

                    }
                }
                System.out.println(Thread.currentThread()+" flag is false. running @"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
            }
        }, "WaitThread");
        waitThread.start();
        TimeUnit.SECONDS.sleep(1);
        Thread notifyThread = new Thread(() -> {
            synchronized (lock) {
                // 获取锁，然后通知，通知时不会释放lock锁
                System.out.println(Thread.currentThread()+" hold lock. notify @"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
                lock.notifyAll();
                flag=false;
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            // 再次加锁
            synchronized (lock) {
                System.out.println(Thread.currentThread()+" hold lock again. notify @"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "NotifyThread");
        notifyThread.start();
    }
}
